#coding=utf-8
from PyQt4 import QtGui,QtCore
import time,re,os,threading as th,Queue
#face class
tl = th.RLock()
typeimg =  {'gif':'image/gif','bmp':'image/bmp','jpg':'image/jpeg'}

class getqqface(th.Thread):
    def __init__(self, queue,myclass,mydata):
        th.Thread.__init__(self)
        self.queue = queue
        self.myclass = myclass
        self.mydata = mydata
        self.typeimg =  typeimg
        self.dir = './data/tw/{0}/face'.format(mydata.get('qq'))
        if os.path.exists(self.dir) == False:
            os.mkdir(self.dir)
        self.listimg = os.listdir(self.dir)
        self.setName('qqface')
    def qq(self,uin):
        try:
            uin['qq'] = self.myclass.getG().get_friend_uin2(uin['uin'],1)['result']['account']
        except Exception:
            return False
        #ValueError:
        return True
    def qqface(self,uin):
        t = (uin['g'],uin['i'])
        simg = None
        #这个查询为本地缓存查询
        for y in self.listimg:
            rstr = re.search('{0}.*'.format(uin['qq']),y)
            if rstr is not None:
                simg = rstr.group()
                simg = '{0}/{1}'.format(self.dir,simg)
                del rstr
                break
            pass
        #没有缓存就重新下载图标
        if simg is None:
            data = self.myclass.getG().getface(uin['uin'])
            for i in self.typeimg:
                if ('%s'% data[1]).find(self.typeimg[i]) != -1:
                    img = i #获取头像图片类型
                    break
            #在这里为图标添加数据
            simg = '{0}/{1}.{2}'.format(self.dir,uin['qq'],img)
            f = open(simg,'wb')
            f.write(data[0])
            f.close()
            del data,f,img
            uin['img'] = simg
        self.ta.ui.treeqq.emit(QtCore.SIGNAL("triggleface"), t[0],t[1],simg)
        del simg,t
    def run(self):
        global tl
        self.ta = self.mydata.get('main','gui')
        t = self.mydata.get('sorttype') #分组
        l = self.mydata.get('sortlist') #好友列表
        for e in t:
            for i in l[t[e]['index']]:
                self.queue.put(l[t[e]['index']][i])
                if tl.acquire():
                    uin = self.queue.get()
                    if self.qq(uin):
                        self.qqface(uin) #保存头像图片
                    del uin
                    self.queue.task_done() #完成一个任务，转换到下一个
                    tl.release()
        self.queue.join()
        del t,l
class getgroupface(th.Thread):
    def __init__(self,queue,myclass,mydata):
        th.Thread.__init__(self)
        self.queue = queue
        self.myclass = myclass
        self.mydata = mydata
        self.typeimg =  typeimg
        self.dir = './data/tw/{0}/gface'.format(mydata.get('qq'))
        if os.path.exists(self.dir) == False:
            os.mkdir(self.dir)
        self.listimg = os.listdir(self.dir)
        self.setName('groupface')
    def group(self,uin):
        try:
            uin['qqgroup'] = self.myclass.getG().get_friend_uin2(uin['code'],4)['result']['account']
        except Exception:
            return False
        #ValueError:
        return True
    def groupface(self,uin):
        simg = None
        #这个查询为本地缓存查询
        for y in self.listimg:
            rstr = re.search('{0}.*'.format(uin['qqgroup']),y)
            if rstr is not None:
                simg = rstr.group()
                simg = '{0}/{1}'.format(self.dir,simg)
                del rstr
                break
            pass
        #没有缓存就重新下载图标
        if simg is None:
            data = self.myclass.getG().getface(uin['code'],4)
            for i in self.typeimg:
                if ('%s'% data[1]).find(self.typeimg[i]) != -1:
                    img = i #获取头像图片类型
                    break
            #在这里为图标添加数据
            simg = '{0}/{1}.{2}'.format(self.dir,uin['qqgroup'],img)
            f = open(simg,'wb')
            f.write(data[0])
            f.close()
            del data,f,img
        uin['img'] = simg
        self.ta.ui.treeqq.emit(QtCore.SIGNAL("trigglegface"),uin['i'],simg)
        del simg
    def run(self):
        global tl
        self.ta = self.mydata.get('main','gui')
        g = self.mydata.get('groupsortlist') #群组列表
        for e in g:
            self.queue.put(g[e])
            if tl.acquire():
                uin = self.queue.get()
                if self.group(uin):
                    self.groupface(uin) #保存头像图片
                del uin
                self.queue.task_done() #完成一个任务，转换到下一个
                tl.release()
        self.queue.join()
        del g
def getfacemethod(myclass,mydata):
    queue = Queue.Queue()
    queue.maxsize = 10
    mydata.set('face',queue,'thread')
    gg = getgroupface(queue,myclass,mydata)
    gg.setDaemon(True)
    gg.start()
    gg.join()
    tt = getqqface(queue,myclass,mydata)
    tt.setDaemon(True)
    tt.start()
    tt.join()



